<template>
  <div class="wapper">
    <div class="f">
      <el-form
        ref="formRef"
        style="max-width: 600px"
        :model="form"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item
          label="姓名"
          prop="username"
          :rules="[
            { required: true, message: '姓名不能为空', trigger: 'blur' },
            { pattern: /[\u4e00-\u9fa5]/, message: '请输入中文', trigger: 'blur' },
          ]"
        >
          <el-input
            placeholder="输入姓名"
            v-model="form.username"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="工号"
          prop="workNumber"
          :rules="[{ required: true, message: '工号不能为空', trigger: 'blur' }]"
        >
          <el-input
            disabled
            placeholder="工号"
            v-model="form.workNumber"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
          :rules="[
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
          ]"
        >
          <el-input
            placeholder="输入手机号"
            v-model="form.mobile"
          disabled
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <!-- //##级联选择部门 -->
        <el-form-item
          label="部门"
          prop="departmentId"
          :rules="[{ required: true, message: '部门必选', trigger: 'blur' }]"
        >
          <el-cascader v-model="val" :options="options" @change="handleChange" />
        </el-form-item>

        <el-form-item
          label="聘用形式"
          prop="formOfEmployment"
          :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
        >
          <el-select
            v-model="form.formOfEmployment"
            placeholder="聘用形式"
            style="width: 240px"
          >
            <el-option :key="1" label="正式" :value="1" />
            <el-option :key="2" label="非正式" :value="2" />
          </el-select>
        </el-form-item>
        <!-- 入职时间 -->
        <el-form-item
          label="入职时间"
          prop="timeOfEntry"
          :rules="[{ required: true, message: '时间必填', trigger: 'blur' }]"
        >
          <el-date-picker
            v-model="form.timeOfEntry"
            type="date"
            placeholder="请选择时间"
            size="default"
            value-format="YYYY-MM-DD"
          />
          <!-- 转正时间 -->
        </el-form-item>
        <el-form-item
          label="入职时间"
          prop="correctionTime"
          :rules="[{ required: true, message: '时间必填', trigger: 'blur' }]"
        >
          <el-date-picker
            v-model="form.correctionTime"
            type="date"
            placeholder="请选择时间"
            size="default"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="员工头像" prop="staffPhoto">
          <div>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="imgChange"
            >
              <img v-if="form.staffPhoto" :src="form.staffPhoto" class="avatar" />
              <div v-else class="uploade-icon">
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 确认添加 -->
        <el-button
          type="primary"
          style="margin-left: 30px;margin-bottom:30px;"
          @click="edit"
          >确认修改</el-button
        >
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
let router = useRouter();
let route = useRoute();
import { ElMessage } from "element-plus";
import axios from "@/utils/request.ts";
import { Plus } from "@element-plus/icons-vue";

const formRef = ref();
let form = ref({
  username: "",
  mobile: "",
  formOfEmployment: undefined,
  workNumber: undefined, //员工工号
  departmentId: undefined, //部门id
  timeOfEntry: "", //入职时间
  correctionTime: "", //转正时间
  staffPhoto: "",
});
let treeArr = ref([]);
let val = ref([]);
const options = ref([]);
let imageUrl = ref("");

// 选中部门的时候
function handleChange(value) {
  // console.log(value); //这是一个数组
  form.departmentId = value[value.length - 1];
}

onMounted(() => {
  // 部门信息
  getDepartment();
  //   员工详情
  getStaffDetail(route.query.id);
});

//## 图片上传事件
function imgChange(file) {
  // 判断图片类型
  // 图片的正则
  let reg = /^image\/(jpeg|png|jpg|gif|bmp|svg|webp)$/;
  // 判断图片类型
  if (!reg.test(file.raw.type)) {
    ElMessage.error("图片格式不正确");
    return;
  }
  // 判断图片大小
  if (file.raw.size > 2 * 1024 * 1024) {
    ElMessage.error("图片大小不能超过2M");
    return;
  }

  // 图片上传成功后，将图片转成base64

  // 将图片转成base64
  let reader = new FileReader();
  reader.readAsDataURL(file.raw);
  reader.onload = function () {
    form.value.staffPhoto = reader.result;
    // console.log(form.value);
  };
}
//##获取部门
function getDepartment() {
  //获取部门
  axios.get("/company/department").then((res) => {
    // console.log(res);
    if (res.success) {
      // 使用无限级分类
      let arr = createCategoryTree(res.data);
      //   console.log(arr);
      options.value = digui(arr);
      // console.log(digui(arr));
      axios.get(`/sys/user/${route.query.id}`).then((re) => {
        if (re.success) {
          let obj = res.data.find((item) => item.id == re.data.departmentId);
          getParentIds(obj, res.data);
        }
      });
    }
  });
}

function getParentIds(obj, arr) {
  // console.log(obj);
  if (obj.pid == 0) {
    val.value.unshift(obj.id);
    return;
  } else {
    val.value.unshift(obj.id);
    arr.forEach((k) => {
      if (k.id == arr.find((i) => i.id == obj.pid).id) {
        // console.log(k, "kkkkkkkk");
        getParentIds(k, arr);
      }
    });
  }
}

// 获取员工详情
function getStaffDetail(id) {
  axios.get(`/sys/user/${id}`).then((res) => {
    console.log(res);
    if (res.success) {
      form.value = res.data;
      // val.value = [res.data.departmentId]
      // console.log(val.value);
      // console.log(form.value.departmentId);
    }
  });
}

// 递归函数，用于改变数组结构
function digui(arr) {
  let newArr = [];
  arr.forEach((k) => {
    let obj = {};
    obj.value = k.id;
    obj.label = k.name;
    if (k.children.length > 0) {
      // console.log(k.children);
      obj.children = digui(k.children);
    }
    newArr.push(obj);
  });
  return newArr;
}

// 定义一个函数 createCategoryTree，用于将平面的分类数据转换为树形结构(无限级分类)
const createCategoryTree = (categories) => {
  // 创建一个对象 categoryMap 用于存储每个分类的节点信息，以分类的 id 作为键
  let categoryMap = {};
  // 创建一个对象 root 用于存储根节点信息，根节点即父节点 pid 为 0 的节点
  let root = {};
  // 遍历分类数据，为每个分类创建一个节点对象，并存储到 categoryMap 中
  categories.forEach((item) => {
    // 创建节点对象，包含分类本身的所有信息和一个空的 children 数组用于存储子节点
    const node = { ...item, children: [] };
    // 将节点对象存储到 categoryMap 中，键为分类的 id
    categoryMap[item.id] = { ...node };
    // 如果当前节点的父节点 id（pid）为 0，说明它是一个根节点，将其存储到 root 对象中
    if (item.pid === 0) {
      root[item.id] = { ...node };
    }
  });
  // console.log(categoryMap);
  // console.log(root);
  // 再次遍历分类数据，将每个节点添加到其父节点的 children 数组中
  categories.forEach((item) => {
    // 如果节点的父节点 id（pid）不为 0，说明它不是根节点
    if (item.pid !== 0) {
      // console.log(item);
      // 通过 pid 从 categoryMap 中找到父节点对象
      const parent = categoryMap[item.pid];
      // console.log(parent);
      // 从 categoryMap 中找到当前节点对象
      const child = { ...categoryMap[item.id] };
      // 将当前节点对象添加到父节点的 children 数组中
      parent?.children.push({ ...child });
    }
  });
  //   console.log(root);
  // 从 root 对象中提取所有根节点的数组
  let arr = Object.values(root);
  // 返回根节点数组，这个数组构成了分类的树形结构
  return arr;
};


// ##发送修改请求
function edit() {
  //   console.log(form);
  formRef.value.validate(async (valid) => {
    if (valid) {
      let obj = { ...form.value, id: route.query.id * 1 };
      console.log(obj,'678768');
      console.log(route.query.id);
      //   let res = await axios.post(`/sys/user/${String(route.query.id)}`, {
      let res = await axios.put(`/sys/user/${route.query.id}`, {
        ...form.value,
      });
      console.log(res);
      if (res.success) {
        ElMessage.success("修改成功");
        router.push("/staff");
      }
      // if (res.code == 200) {
      //   ElMessage.success("添加成功");
      //   dialogVisible.value = false;
      //   getCategory();
      // }
    }
  });
}
</script>

<style scoped lang="less">
.wapper {
  background-color: #fff;
  height: 100%;
  padding-left: 200px;
  .f {
    width: 500px;
    // height: 100%;
    // background-color: rgb(0, 251, 255);
    padding-top: 30px;
  }
}
.icon {
  width: 35px;
  height: 35px;
}
.uploade-icon {
  height: 200px;

  border: 2px #e0e0e0 dashed;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 30px;
}
.avatar {
  width: 200px;
  height: 200px;
  border-radius: 30px;
}
.el-form-item {
  margin-bottom: 40px;
}
</style>
